package com.net.common.enums.mybatis;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.net.common.enums.EnumUtil;
import com.net.common.enums.base.IntEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.net.common.enums.base.StringEnum;

/**
 * @author  on 08/02/2018.
 */
public class CustomEnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

    private final Class<E> type;

    public CustomEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        if (IntEnum.class.isAssignableFrom(type)) {
            ps.setInt(i, ((IntEnum) parameter).getValue());
        } else if (StringEnum.class.isAssignableFrom(type)) {
            ps.setString(i, ((StringEnum) parameter).getValue());
        } else {
            ps.setString(i, parameter.name());
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if (isIntEnum()) {
            return EnumUtil.getIntEnum(rs.getInt(columnName), type);
        } else if (isStringEnum()) {
            String s = rs.getString(columnName);
            return s == null ? null : EnumUtil.getStringEnum(s, type);
        } else {
            String s = rs.getString(columnName);
            return s == null ? null : Enum.valueOf(type, s);
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        if (isIntEnum()) {
            return EnumUtil.getIntEnum(rs.getInt(columnIndex), type);
        } else if (isStringEnum()) {
            String s = rs.getString(columnIndex);
            return s == null ? null : EnumUtil.getStringEnum(s, type);
        } else {
            String s = rs.getString(columnIndex);
            return s == null ? null : Enum.valueOf(type, s);
        }
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if (isIntEnum()) {
            return EnumUtil.getIntEnum(cs.getInt(columnIndex), type);
        } else if (isStringEnum()) {
            String s = cs.getString(columnIndex);
            return s == null ? null : EnumUtil.getStringEnum(s, type);
        } else {
            String s = cs.getString(columnIndex);
            return s == null ? null : Enum.valueOf(type, s);
        }
    }

    private boolean isStringEnum() {
        return StringEnum.class.isAssignableFrom(type);
    }

    private boolean isIntEnum() {
        return IntEnum.class.isAssignableFrom(type);
    }
}
